
import path from 'path'
import fs from 'fs-extra'
import ini from 'ini'
import _ from 'lodash'

export const HOME = process.env.HOME || process.env.HOMEPATH

export const GMC_PATH = path.resolve(HOME, '.gmc')

export const GMC_CONFILE = path.resolve(GMC_PATH, 'config')

const getConfig = () => {
  try {
    return ini.parse(fs.readFileSync(GMC_CONFILE, 'utf-8'))
  } catch (error) {
    return null
  }
}

export const GMC_CONF = getConfig()

export const getProjectList = () => {
  let projectList = []
  for (let item of _.keys(GMC_CONF)) {
    let info = GMC_CONF[item]
    projectList.push(`[${item}] -- ${info.name}`)
  }
  return projectList
}

export const getSocketList = (project) => {
  let socketList = []
  let projectConf = GMC_CONF[project]
  let socketConf = projectConf.socket || {}
  for (let item of _.keys(socketConf)) {
    let info = socketConf[item]
    socketList.push(`[${item}] -- ${info.name} -- ${info.rtsp}`)
  }
  return socketList
}

export const getInterfaces = (tag) => {
  let pathname = GMC_CONF[tag].path
  let interfacePath = path.resolve(GMC_PATH, pathname, 'api')
  let interfaceFiles = []
  if (fs.existsSync(interfacePath)) {
    interfaceFiles = _.filter(fs.readdirSync(interfacePath), o => /\.(ini)$/.test(o))
  }
  let interfaces = null
  for (let item of interfaceFiles) {
    interfaces = {
      ...interfaces,
      ...ini.parse(fs.readFileSync(path.resolve(interfacePath, item), 'utf-8'))
    }
  }
  return interfaces
}

export const getInterfaceList = (tag) => {
  let interfaces = getInterfaces(tag)
  let interfaceList = []
  for (let item of _.keys(interfaces)) {
    let info = interfaces[item]
    interfaceList.push(`[${item}] -- ${info.msg}`)
  }
  return interfaceList
}